import 'dart:io';

import 'package:chewie/chewie.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import 'index.dart';

class VideoFullPlayerController extends GetxController {
  VideoFullPlayerController();

  final state = VideoFullPlayerState();

  Future<void> initialize() async {
    if (state.url?.isNotEmpty != true) return;

    if (state.url!.startsWith('http')) {
      state.vpc = VideoPlayerController.networkUrl(Uri.parse(state.url!));
    } else {
      state.vpc = VideoPlayerController.file(File(state.url!));
    }
    await state.vpc.initialize();
    state.controller = ChewieController(
      videoPlayerController: state.vpc,
      autoPlay: true,
    );
    update();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    // 强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    super.onInit();
    state.title = Get.arguments['title'] ?? '';
    state.url = Get.arguments['url'];
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
    initialize();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
    state.vpc.dispose();
    state.controller?.dispose();
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }
}
